<template>
    <div>
      <!--<div class="crumbs">
          <el-breadcrumb separator="/">
              <el-breadcrumb-item><i class="el-icon-setting"></i> 系统管理</el-breadcrumb-item>
                <el-breadcrumb-item>{{$route.meta.displayName}}</el-breadcrumb-item>
          </el-breadcrumb>
      </div>-->
      <el-row :gutter="10" type="flex" class="row-bg" justify="space-between">
          <el-col :xs="8" :sm="6" :md="8" :lg="9">
            <div class="grid-content bg-purple">
              <el-input placeholder="请输入内容"   icon="search" v-model="roleSearch" :on-icon-click="handleSearchClick">>
                <el-select v-model="search_select" slot="prepend" clearable  placeholder="请选择">
                  <el-option label="角色名" value="roleName"></el-option>
                </el-select>
              </el-input>
            </div>
          </el-col>
          <el-col :xs="8" :sm="6" :md="4" :lg="3"><el-button type="primary" @click="handleAddRoleClick" icon="el-icon-plus">新增角色</el-button></el-col>
      </el-row>
      <el-row type="flex" class="row-bg" justify="center">
        <el-col :span="24">
          <div class="grid-content bg-purple">
            <el-table
                :data="roleData"
                max-height="500"
                style="width: 100%">
                <el-table-column
                  @resizable ="resizable"
                  prop="name"
                  label="角色名"
                  min-width="180">
                </el-table-column>
                <el-table-column
                  @resizable ="resizable"
                  prop="note"
                  label="备注"
                  min-width="180">
                </el-table-column>
                <el-table-column
                  resizable
                  label="操作"
                  min-width="300">
                  <template scope="scope">
                    <el-button @click="handleModifyRoleClick(scope.$index,scope.row)" type="text" icon="edit" size="small">编辑</el-button>
                    <el-button @click="handleSignUserToRoleClick(scope.$index,scope.row)" type="text" size="small">分配用户</el-button>
                    <el-button @click="handleFindMenusOfRoleClick(scope.$index,scope.row)" type="text" size="small"> 功能菜单权限</el-button>
                    <el-button @click="handleDelRoleClick(scope.$index,scope.row)" type="text" size="small"> 删除</el-button>
                  </template>
                </el-table-column>
                </el-table>
          </div>
        </el-col>
      </el-row>
      <el-row type="flex" justify="end">
          <el-col :span="12">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="pageSizes"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next"
              :total="total">
            </el-pagination>
        </el-col>
      </el-row>

      <el-dialog :title="dialogTitle" :close="handleDialogCloseClick"  v-model="dialogRoleDataVisible" class="demo-box demo-ruleForm">
          <el-row type="flex" justify="center">
              <el-col :span="24">
                <el-form :model="singleRoleDataForm" :rules="roleDataValidRules"  ref ="singleRoleDataForm">
                  <el-form-item prop="name" label-position="right" label="角色名:" :label-width="formLabelWidth"  >
                    <el-input v-model="singleRoleDataForm.name" auto-complete="off"></el-input>
                  </el-form-item>
                  <el-form-item prop="note" label-position="right" label="备注:" :label-width="formLabelWidth">
                    <el-input v-model="singleRoleDataForm.note" auto-complete="off"></el-input>
                  </el-form-item>
                  <el-form-item label="有效性" label-position="right" :label-width="formLabelWidth"  prop="active">
                    <el-switch on-text="是" off-text="否" v-model="singleRoleDataForm.active"></el-switch>
                  </el-form-item>
                </el-form>

              </el-col>
          </el-row>
          <div slot="footer" v-if="dialogTitle =='新增角色'" class="dialog-footer">
            <el-button @click="handleCancleSubmitForm('singleRoleDataForm')">取 消</el-button>
            <el-button type="primary" @click="handleAddRoleDataActionForm('singleRoleDataForm')">确 定</el-button>
          </div>
          <div slot="footer" v-else class="dialog-footer">
            <el-button @click="handleCancleSubmitForm('singleRoleDataForm')">取 消</el-button>
            <el-button type="primary" @click="handleModifyRoleDataActionForm('singleRoleDataForm')">修改</el-button>
          </div>
              <!-- @current-change = "handleMenuAuthorityCurrentChangeClick" -->
      </el-dialog>

      <el-dialog title="功能菜单权限" :close="handleDialogCloseClick" v-model="dialogMenuAuthorityVisible" class="demo-box demo-ruleForm">
          <el-row type="flex" justify="center">
              <el-col :span="24">

                <el-tree
                  show-checkbox
                  default-expand-all
                  :props="menuAuthorityProps"
                  :data="menuAuthorityData"
                  :expand-on-click-node = "false"
                  :highlight-current ="true"
                  node-key ="id"
                  :check-strictly="true"

                  @check-change = "handleMenuAuthorityCheckChangeClick"
                  ref="menuAuthorityData">
                </el-tree>

              </el-col>
          </el-row>
      </el-dialog>


        <el-dialog title="分配用户"  v-model="dialogSignUserToRoleVisible" class="demo-box demo-ruleForm">
          <el-row type="flex" class="row-bg" justify="center">
            <el-col :span="24">
            <div class="grid-content bg-purple"><h4>已有用户</h4></div>
            <div class="grid-content bg-purple">
                <el-table
                    :data="userData"
                    border
                    max-height="300"
                    style="width: 100%">
                    <el-table-column
                      @resizable ="resizable"
                      prop="name"
                      label="用户名"
                      min-width="25%">
                    </el-table-column>
                    <el-table-column
                      @resizable ="resizable"
                      prop="name"
                      label="用户名称"
                      min-width="25%">
                    </el-table-column>
                    <el-table-column
                      resizable
                      label="操作"
                      min-width="50%">
                      <template scope="scope">
                        <el-button @click="handleRemoveUserOfRoleClick(scope.$index,scope.row)" type="text" icon="edit" size="small">移除</el-button>
                      </template>
                    </el-table-column>
                    </el-table>
              </div>
            </el-col>
          </el-row>
          <el-row type="flex" justify="end">
              <el-col :span="12">
                <el-pagination
                  @size-change="handleUserDataSizeChange"
                  @current-change="handleUserDataCurrentChange"
                  :current-page="userDataPagination.currentPage"
                  :page-sizes="userDataPagination.pageSizes"
                  :page-size="userDataPagination.pageSize"
                  layout="total, sizes, prev, pager, next"
                  :total="userDataPagination.total">
                </el-pagination>
            </el-col>
          </el-row>

          <el-row type="flex" class="row-bg" justify="center">
            <el-col :span="24">
              <div class="grid-content bg-purple"><h5>可选用户</h5></div>
              <div class="grid-content bg-purple">

                <el-table
                    :data="availableUser"
                    border
                    max-height="300"
                    style="width: 100%">
                    <el-table-column
                      @resizable ="resizable"
                      prop="name"
                      label="用户名"
                      min-width="25%">
                    </el-table-column>
                    <el-table-column
                      @resizable ="resizable"
                      prop="name"
                      label="用户名称"
                      min-width="25%">
                    </el-table-column>
                    <el-table-column
                      resizable
                      label="操作"
                      min-width="50%">
                      <template scope="scope">
                        <el-button @click="handleSignAvailableUserToRoleClick(scope.$index,scope.row)" type="text" icon="edit" size="small">上移</el-button>
                      </template>
                    </el-table-column>
                </el-table>
              </div>
            </el-col>
          </el-row>
          <el-row type="flex" justify="end">
              <el-col :span="12">
                <el-pagination
                  @size-change="handleAvailableUserSizeChange"
                  @current-change="handleAvailableUserCurrentChange"
                  :current-page="availableUserPagination.currentPage"
                  :page-sizes="availableUserPagination.pageSizes"
                  :page-size="availableUserPagination.pageSize"
                  layout="total, sizes, prev, pager, next"
                  :total="availableUserPagination.total">
                </el-pagination>
            </el-col>
          </el-row>
        </el-dialog>


    </div>
</template>



<script>
  import RoleService from 'api/security/role';
  export default {
    data :function(){
      return {
        //table
        roleData:[],
        currentPage:1,
        pageSizes:[10,20],
        pageSize:10,
        total:0,
        dialogRoleDataVisible:false,
        //搜索
        roleSearch:'',
        //搜索下拉选择
        search_select:'',

        formLabelWidth:'30%',

        dialogTitle:'新增角色',
        singleRoleDataForm:{
            id:'',
            name:'',
            note:'',
            active:false,
        },
        roleDataValidRules:{
          name:[{
              required: true,
              message: '角色名称不能为空',
              trigger: 'blur'
          }]
        },
        //功能菜单权限
        dialogMenuAuthorityVisible:false,
        menuAuthorityProps:{
          children:'children',
          label:'name'
        },
        menuAuthorityData:[], //所点击分配菜单权限的 角色的所拥有的菜单
        allAuthorities:[],//所有的功能权限菜单
        // userClickChecked:false ,//用户点击的 Checked
        authorityIds:[],//
        existAuthorities:[],//当前role 已经存在的菜单权限
        singleSelectRow:[], //当前 选择行
        //分配额用户
        dialogSignUserToRoleVisible:false,
        userData:[],
        availableUser:[],
        userDataPagination:{
          currentPage:1,
          pageSizes:[10,20],
          pageSize:10,
          total:0,
        },
        //可分配用户table 的Pagination
        availableUserPagination:{
          currentPage:1,
          pageSizes:[10,20],
          pageSize:10,
          total:0,
        },

      };

    },
    methods:{
      handleDialogCloseClick(){
        // this.userClickChecked = false ;
        this.dialogRoleDataVisible =false;
        this.singleRoleDataForm = {
            id:'',
            name:'',
            note:'',
            active:false,
        };
        this.authorityIds = [];
        this.menuAuthorityData = [];
        this.existAuthorities= [];
        this.singleSelectRow = [];
      },
      handleMenuAuthorityClick(data ,node){
      },
      handleMenuAuthorityCheckChangeClick(data ,node){

        var self = this;
        if (this.authorityIds.includes(data.id) && node){
          //非人点击
          this.authorityIds = this.authorityIds.filter((value) =>{
            return value != data.id;
          });
        }else{
          //人点击
          if(node){
              //菜单赋予权限
              //根据
              let params = {
                authorityId: data.id,
                roleId:self.singleSelectRow.id
              };
              RoleService.signAuthorityToRole(params).then((response) =>{
                if (response.data!=null && response.data.errorCode==null){
                  self.$message({
                    type:"success",
                    message:"分配成功"
                  });
                  this.existAuthorities.push(response.data);
                }
              }).catch(err =>{
                  self.$message({
                    type:"error",
                    message:"操作失败"
                  });
              });
          }else{
            //取消菜单权限分配
            let tmpexistAuthorities = this.existAuthorities ;
            let tmpArr =  tmpexistAuthorities.filter((item) =>{
              return item.authorityId == data.id;
            });
            if (tmpArr.length > 0){
              let params = {
                id:tmpArr[0].id
              };
              RoleService.delRoleAuthority(params).then( (response) =>{
                self.$message({
                  type:"success",
                  message:"成功取消该权限的分配"
                });
                //重数组中删除
                this.existAuthorities =tmpexistAuthorities.filter((item)=>{
                  return item.id !=tmpArr[0].id ;
                });
              }).catch(err =>{
                self.$message({
                  type:"error",
                  message:"操作失败"
                });
              });
            }

          }


        }
      },
      handleMenuAuthorityCurrentChangeClick(data ,node){
      },
      handleCancleSubmitForm(formName){
          this.dialogRoleDataVisible =false;
          this.$message({
            message:"操作取消",
            type:"info"
          });
          this.singleRoleDataForm={
              id:'',
              name:'',
              note:'',
              active:false,
          };
      },
      //增加角色信息的dialogform按钮事件
      handleAddRoleDataActionForm(formName){

          this.roleDataAction(formName,null);
      },
      //修改角色信息的dialogform按钮事件
      handleModifyRoleDataActionForm(formName){
          this.roleDataAction(formName,'modify');
      },
      roleDataAction(formName,action=null,dialogModeName="dialogRoleDataVisible"){
        var self = this;
        this.$refs[formName].validate( (valid)=>{
            if (valid) {
                //保存数据
                var params = {
                    name : self.singleRoleDataForm.name,
                    note:self.singleRoleDataForm.note,
                    active:self.singleRoleDataForm.active==true ? 1:0
                };
                var msg ="添加成功";
                if (action !=null){
                    params.id = self.singleRoleDataForm.id;
                    msg = "修改角色成功"
                }
                RoleService.saveRoleData(params).then((response)=>{

                    if (response.data.errorCode == null){
                      self.$message({
                          message: msg,
                          type: "success"
                      });
                      //重置表单
                      self[formName]={
                          id:'',
                          name:'',
                          note:'',
                          active:false,
                      };
                      //刷新 用户列表
                      self[dialogModeName] = false;
                      self.pageQueryRoleData(1,10);
                    }

                }).catch(err=>{
                    self.$message({
                        message: "操作失败",
                        type: "error"
                    });
                });
              //

            }else{
              return false ;
            }
        });

      },


      handleAddRoleClick(ev){
        this.dialogTitle = "新增角色";
        this.singleRoleDataForm = {
            id:'',
            name:'',
            note:'',
            active:false,
        };
        this.dialogRoleDataVisible = true;

      },

      //修改 角色信息按钮 点击事件
      handleModifyRoleClick(index,row){
          this.dialogTitle = "修改角色信息";
          this.dialogRoleDataVisible = true;
          let {id ,name ,note  } = row ;
          let active = row.active == 1 ?true :false ;
          this.singleRoleDataForm = {id ,name ,note ,active } ;
      },
      handleSignUserToRoleClick(index,row){
          this.$message({
            type:'info',
            message:'分配用户'
          });

          //打开dialog
          this.dialogSignUserToRoleVisible = true ;

          //的到已有用户信息
          var params = {
            id : row.id
          };
          this.pageQueryExistUserDataByRole(params);
          //的到可分配用户列表

          this.pageQueryAvailableUserDataByRole(params);



      },
      handleFindMenusOfRoleClick(index,row){
        this.$message({
          type:'info',
          message:'分配菜单'
        });

        //从服务器端获取到 功能权限数据
        var self =this ;


        RoleService.findAllAuthorities().then(response =>{
          if (response.data!=null &&response.data.errorCode == null){

            self.menuAuthorityData = response.data;
            self.existAuthorities = [];
            self.authorityIds = [];
            self.singleSelectRow = row ;
            self.dialogMenuAuthorityVisible = true ;
            if ( response.data.length == 0){

            }else{

                //清空 树形菜单 checked
              // _self.$refs.menuAuthorityData.setCheckedKeys([]);
              //根据 role id 找到该role 所拥有的菜单权限
              var params = {id :row.id};
              RoleService.findAuthoritiesByRole(params).then(response =>{
                  if (response.data!=null &&response.data.errorCode == null){

                      // var authorityIds=[];

                      response.data.forEach((item) =>{
                        self.authorityIds.push(item.authorityId);
                      });
                      self.existAuthorities =  response.data;
                      // self.authorityIds =authorityIds ;

                      self.$refs.menuAuthorityData.setCheckedKeys(self.authorityIds)

                  }
              }).catch(err =>{

              });
            }
          }
        }).catch(err =>{

        });





      },
      handleDelRoleClick(index,row){
        var self = this ;
        var confirmInfo = "此操作将删除角色:"+row.name+", 是否继续?";
        this.$confirm(confirmInfo, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            if (row.id !=null) {
              var params = {
                id : row.id
              }
              RoleService.delRoleData(params).then(response =>{
                self.$message({
                  type: 'success',
                  message: '删除成功!'
                });
                //刷新用户列表
                self.pageQueryRoleData(1,10);
              }).catch(err=>{
                self.$message({
                  type: 'error',
                  message: '删除失败!'
                });
              });
            }


          }).catch(() => {
            self.$message({
              type: 'info',
              message: '已取消删除'
            });
          });
      },
      resizable(){
        return false;
      },
      //搜索handle
      handleSearchClick(ev){
        //模糊搜索
        this.$message({
          type:"info",
          message:"搜索"
        })

      },
      handleSignAvailableUserToRoleClick(index ,row){
          var self = this;
          let params = {
            userId:row.id ,
            roleId:row.roleId
          };
          RoleService.signUserToRole(params).then(response =>{
            if (response.data!=null &&response.data.errorCode == null){
                self.$message({
                  message:"分配用户成功",
                  type:"success"
                });

                //刷新列表
                self.pageQueryExistUserDataByRole({id:row.roleId});
                self.pageQueryAvailableUserDataByRole({id:row.roleId});

            }else{
              self.$message({
                message:"分配用户失败",
                type:"error"
              });

            }

          }).catch( err =>{
            console.log(err);
            self.$message({
              message:"操作失败",
              type:"error"
            })
          });
      },
      handleRemoveUserOfRoleClick(index,row){
        var self = this;
        let params = {
          id:row.ruid
        };
        RoleService.delRoleAndUserRelationship(params).then(response =>{
          if (response.data==null){
              self.$message({
                message:"成功取消该用户此角色的权限",
                type:"success"
              });
              //刷新列表
              self.pageQueryExistUserDataByRole({id:row.roleid});
              self.pageQueryAvailableUserDataByRole({id:row.roleid});

          }else{
            self.$message({
              message:"操作失败",
              type:"error"
            });

          }

        }).catch( err =>{
          console.log(err);
          self.$message({
            message:"操作失败",
            type:"error"
          })
        });


      },
      handleUserDataCurrentChange(val){

      },
      handleUserDataSizeChange(val){

      },
      handleAvailableUserCurrentChange(val){

      },
      handleAvailableUserSizeChange(val){

      },
      handleSizeChange(val){
        this.pageSize = val;
        this.pageQueryRoleData(this.currentPage,this.pageSize);
      },
      handleCurrentChange(val){
        this.currentPage = val;
        this.pageQueryRoleData(this.currentPage,this.pageSize);
      },
      pageQueryRoleData(pageIndex=1,pageSize=10){
        var self = this;
        RoleService.pageQueryRoleData({},pageIndex,pageSize).then(response =>{
            if (response.data.rows !=null ){

              self.roleData =response.data.rows ;
              self.currentPage = response.data.pageIndex;
              self.pageSize = response.data.pageSize ;
              self.total = response.data.total;
            }

        }).catch(err =>{
            console.log(err);
        });
      },
      findAllAuthorities(){
        var self =this ;
        RoleService.findAllAuthorities().then(response =>{
          if (response.data!=null &&response.data.errorCode == null){
            self.menuAuthorityData = response.data ;
          }
        }).catch(err =>{

        });
      },
      //分页查询 角色已有用的用户
      pageQueryExistUserDataByRole(params,pageIndex =1 ,pageSize = 10){
        var self = this;
        RoleService.pageQueryExistUserDataByRole(params,pageIndex,pageSize).then(response =>{
            if(response.data!=null && response.data.errorCode == null){
              response.data.rows.forEach ((item,index,arr) =>{
                item.roleId = params.id;
                arr[index] = item;
              });
              self.userData = response.data.rows;
              self.userDataPagination.currentPage = response.data.pageIndex;
              self.userDataPagination.pageSize = response.data.pageSize ;
              self.userDataPagination.total = response.data.total;
            }
        }).catch(err =>{

        });

      },
      //分页查询 角色未拥有的用户
      pageQueryAvailableUserDataByRole(params ,pageIndex =1 ,pageSize = 10){
        var self = this;
        RoleService.pageQueryAvailableUserDataByRole(params,pageIndex,pageSize).then(response =>{
            if(response.data!=null && response.data.errorCode == null){
              response.data.rows.forEach ((item,index,arr) =>{
                item.roleId = params.id;
                arr[index] = item;
              });
              self.availableUser = response.data.rows;
              self.availableUserPagination.currentPage = response.data.pageIndex;
              self.availableUserPagination.pageSize = response.data.pageSize ;
              self.availableUserPagination.total = response.data.total;
            }
        }).catch(err =>{

        });

      }

    },
    mounted:function (){
      this.pageQueryRoleData();
      this.findAllAuthorities();
    }


  }
</script>


<style scoped>
  .demo-box .el-select, .demo-box .el-input{
    width:60%;
    float: left;
  }
  .demo-box .el-switch{
    float: left;
  }
  .el-col .el-pagination{
    float: right;
  }
  .el-input .el-select{
    width: 110px;
  }
  .el-row {
    margin-bottom: 20px;
    &:last-child {
      margin-bottom: 0;
    }
  }
  .el-col {
    border-radius: 4px;
  }
  .bg-purple-dark {
    background: #99a9bf;
  }
  .bg-purple {
    background: #d3dce6;
  }
  .bg-purple-light {
    background: #e5e9f2;
  }

</style>
